using MediatR;
using TerritoryGame.Application.Queries;
using TerritoryGame.Domain.Repositories;

namespace TerritoryGame.Application.Handlers.QueryHandlers;

public class GetRoomsQueryHandler : IRequestHandler<GetRoomsQuery, GetRoomsResult>
{
    private readonly IGameRoomRepository _gameRoomRepository;
    
    public GetRoomsQueryHandler(IGameRoomRepository gameRoomRepository)
    {
        _gameRoomRepository = gameRoomRepository;
    }
    
    public async Task<GetRoomsResult> Handle(GetRoomsQuery request, CancellationToken cancellationToken)
    {
        try
        {
            var rooms = await _gameRoomRepository.GetWaitingRoomsAsync();
            
            var roomInfos = rooms.Select(room => new RoomInfo
            {
                Id = room.Id,
                Name = room.Name,
                RoomCode = room.RoomCode, // 添加房间代码
                Password = room.Password,
                MaxPlayers = room.MaxPlayers,
                PlayerCount = room.Players.Count,
                Status = room.Status.ToString(),
                GameDuration = room.GameDuration,
                CreatedAt = room.CreatedAt
            }).ToList();
            
            return new GetRoomsResult
            {
                Success = true,
                Rooms = roomInfos
            };
        }
        catch (Exception ex)
        {
            return new GetRoomsResult
            {
                Success = false,
                ErrorMessage = $"获取房间列表失败: {ex.Message}"
            };
        }
    }
}
